<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use think\Queue;

ini_set('date.timezone','Asia/Shanghai');
define("NOW_TIME",time());
define('MD5_STR','fuel_admin.win10030.COM');
define("WEIXIN_BASE_URL","http://www.10030.com.cn/weixin-callbak/?url=");
define('MQHOST', 'fuel.win10030.com');
define('MQPORT', 5672);
define('MQUSER', 'flow_server');
define('MQPASS', 'iI94RQFGWbqg58GJ');
define('MQVHOST', '/');
function sendQueue($function,$params=[])
{
    $jobHandlerClassName = 'app\job\Task';
    // 2.当前任务归属的队列名称，如果为新队列，会自动创建
    $jobQueueName = "fuelJobQueue";
    // 3.当前任务所需的业务数据 . 不能为 resource 类型，其他类型最终将转化为json形式的字符串
    //   ( jobData 为对象时，需要在先在此处手动序列化，否则只存储其public属性的键值对)
    $jobData = ['ts' => time(), 'function' => $function, 'params' => $params];
    // 4.将该任务推送到消息队列，等待对应的消费者去执行
    return Queue::push($jobHandlerClassName, $jobData, $jobQueueName);
}
function sendMQQueue($routing_key,$messageBody)
{
    try{
//        $exchange = 'router';
        $connection = new AMQPStreamConnection(MQHOST, MQPORT, MQUSER,  MQPASS, MQVHOST);
        $channel = $connection->channel();
//        $channel->queue_declare($queue, false, true, false, false);
//        $channel->exchange_declare($exchange, 'direct', false, true, false);
//        $channel->queue_bind($queue, $exchange);
        $message = new AMQPMessage($messageBody, array('content_type' => 'text/plain', 'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT));
        $channel->basic_publish($message, "",$routing_key);
        $channel->close();
        $connection->close();
        return true;
    }catch (\Exception $e)
    {

    }
    return false;
}
/**
 * @param $list
 * @param string $pk
 * @param string $pid
 * @param int $root
 * @param int $level
 * @return array
 * @internal param string $child
 */
function list_to_tree($list, $pk='id', $pid = 'pid', $root = 0, $level=0) {
    // 创建Tree
    $tree = [];
    if(is_array($list)) {
        // 创建基于主键的数组引用
        foreach($list as $val)
        {
            if($val[$pid] == $root)
            {

                $tree1 = list_to_tree($list, $pk, $pid, $val[$pk],$level+1);
                $val["level_child"] = $level;
                $val["child_size"] = count($tree1);
                $tree[] = $val;
                $tree = array_merge($tree,$tree1);
            }
        }
    }
    return $tree;
}
function array_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0) {
    // 创建Tree
    $tree = array();
    if(is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId =  $data[$pid];
            if ($root == $parentId) {
                $tree[$data[$pk]] =& $list[$key];
            }else{
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][$data[$pk]] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}


function make_array($arr,$key)
{
    $list = [];
    foreach ($arr as $k => $v)
    {
        if(!empty($v[$key]))
        {
            $list[] = $v[$key];
        }
    }
    return $list;
}
function make_array_key($arr,$key,$is_key=false)
{
    $list = [];
    foreach ($arr as $k => $v)
    {
        if(!empty($v[$key]))
        {
//            if(is_object($v))
//                $v = (array) $v;
            if($is_key)
            {
                $list[$v[$key]] = $v;
            }else{
                $list[$v[$key]][] = $v;
            }

        }
    }
    return $list;
}

function double_md5($str) {
    return md5 ( md5 ( trim ( $str ) . MD5_STR ) );
}
function get_date_time($format="Y-m-d H:i:s")
{
    return date($format);
}


function curlPost($url, $curlPost) {
    $curl = curl_init ();
    curl_setopt ( $curl, CURLOPT_URL, $url );
    curl_setopt ( $curl, CURLOPT_HEADER, false );
    curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, true );
    curl_setopt ( $curl, CURLOPT_NOBODY, true );
    curl_setopt ( $curl, CURLOPT_POST, true );
    curl_setopt ( $curl, CURLOPT_POSTFIELDS, $curlPost );
    $return_str = curl_exec ( $curl );
//	var_dump(curl_error($curl));//如果执行curl过程中出现异常，可打开此开关，以便查看异常内容
    curl_close ( $curl );

    return $return_str;
}


function convert_charset($v)
{
    return iconv('utf-8', 'gbk', $v);
}
function putcvs($fp,$list)
{
    foreach ($list as $key=>$val)
    {
        $list[$key] = convert_charset($val);
    }
    fputcsv($fp,$list);
}
function remove_file_order_csv()
{
    $date = get_date_time("YmdH");
    $path = "./files/";
    foreach(scandir($path) as $afile)
    {
        if($afile=='.'||$afile=='..') continue;
        if(file_exists($path.$afile) && !strncmp($afile,"orders_",6) && strncmp($afile,"orders_".$date,18)<0)
        {
            @unlink($path.$afile);
        }
        if(file_exists($path.$afile) && !strncmp($afile,"walletlogs_",11) && strncmp($afile,"walletlogs_".$date,23)<0)
        {
            @unlink($path.$afile);
        }
    }

}

function get_order_no($prefix,$ext="")
{
    if($ext)
        $ext = substr($ext,-4);
    $order_no = $prefix.get_date_time("ymdHis");
    $num = !empty($ext)?3:7;
    for($i=0;$i<$num;$i++)
    {
        $order_no .= mt_rand(0,9);
    }
    return $order_no.$ext;
}
/**
 * 十六进制转为字符
 * @param string $hexdata	十六进制组成的字符串
 * @return string 转化后得到的字符串
 */
function convert_to_char($hexdata) {
    $str = '';
    for($i = 0; $i < strlen($hexdata); $i+=2) {
        $str .= chr(hexdec(substr($hexdata, $i, 2)));
    }
    return $str;
}

/**
 * 字符转换为十六进制
 * @param string $str	字符串
 * @return string
 */
function convert_to_number($str) {
    $length = strlen($str);
    $number_str = '';
    for($i = 0; $i < $length; $i++) {
        $istr = dechex(ord($str[$i]));
        if(strlen($istr) == 1) {
            $istr = '0'.$istr;
        }
        $number_str .= $istr;
    }

    return $number_str;
}

/**
 * rc4加密、解密算法
 * @param string $data	要加密/解密的数据
 * @param string $key	加密/解密的密钥
 * @return string 加密/解密后的数据
 */
function rc4_code($data, $key='1c2bf8d0d5c9a6*@') {
    $seed[] = '';
    $box[]  = '';

    $key_length  = strlen($key);
    $data_length = strlen($data);

    for($i = 0; $i < 256; $i++) {
        $seed[$i] = ord($key[$i%$key_length]);
        $box[$i]  = $i;
    }

    for($j = $i = 0; $i < 256; $i++) {
        $j = ($j+$box[$i]+$seed[$i])%256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }

    $cipher = '';
    for($a = $j = $i = 0; $i < $data_length; $i++) {
        $a = ($a+1)%256;
        $j = ($j+$box[$a])%256;
        $tmp = $box[$a];

        $box[$a] = $box[$j];
        $box[$j] = $tmp;

        $k = $box[(($box[$a]+$box[$j])%256)];
        $cipher .= chr(ord($data[$i])^$k);
    }

    return $cipher;
}

function curl_url($url,$headers=[],$body="")
{
    $result = ["code"=>500,"body"=>"","error_info"=>""];
    try{
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if(!empty($headers))
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        if($body)
        {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        }

        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        if($output === false){
            $result["error_info"]= curl_errno($ch);
        }
        $result["code"] = curl_getinfo($ch,CURLINFO_HTTP_CODE);
        $result["body"] = $output;
        //释放curl句柄
        curl_close($ch);
    }catch (\Exception $e)
    {
        $result["error_info"] = $e->getMessage();
    }
    return $result;
}


function get_card_type($val)
{
    $str = "";
    switch ($val)
    {
        case 0:$str = "老卡";break;
        case 1:$str = "副卡";break;
        case 2:$str = "柴油卡";break;
        default:break;
    }
    return $str;
}
function get_mode($val)
{
    $str = "";
    switch ($val)
    {
        case 0:$str = "充值";break;
        case 1:$str = "开卡";break;
        default:break;
    }
    return $str;
}
function get_pay_status($val)
{
    $str = "";
    switch ($val)
    {
        case 0:$str = "未付款";break;
        case 1:$str = "已付款";break;
        case 2:$str = "付款失败";break;
        default:break;
    }
    return $str;
}
function get_status($val)
{
    $str = "";
    switch ($val)
    {
        case 1:$str = "充值中";break;
        case 2:$str = "充值成功";break;
        case 3:$str = "充值成功";break;
        default:$str = "充值失败";break;
    }
    return $str;
}
function get_delivery_status($val)
{
    $str = "";
    switch ($val)
    {
        case 1:$str = "未发货";break;
        case 2:$str = "发货中";break;
        case 3:$str = "发货完成";break;
        default:$str = "无发货";break;
    }
    return $str;
}
function get_pay_type($val)
{
    $str = "";
    switch ($val)
    {
        case 1:$str = "微信";break;
        case 2:$str = "支付宝";break;
        case 3:$str = "预存款";break;
        case 4:$str = "代理预存款";break;
        case 5:$str = "企业预存款";break;
        case 6:$str = "测试款";break;
        default:$str = "手工付款";break;
    }
    return $str;
}

function get_yes_no($val)
{
    $str = "";
    switch ($val)
    {
        case 0:$str = "否";break;
        case 1:$str = "是";break;
        default:break;
    }
    return $str;
}

function is_mobile( $text ) {
    $search = '/^0?1[0-9]\d{9}$/';
    if ( preg_match( $search, $text ) ) {
        return ( true );
    } else {
        return ( false );
    }
}

function base64EncodeImage ($image_file) {
    $base64_image = '';
    $image_info = getimagesize($image_file);
    $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
    $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
    return $base64_image;
}

function isClient(){
    if (empty($_SERVER['HTTP_USER_AGENT']))
        return false;
    //判断是不是微信
    if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
        return "weixin";
    }
    //判断是不是支付宝
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'AlipayClient') !== false) {
        return "alipay";
    }
    //哪个都不是
    return false;
}
